import { TOKEN } from '@/global/constants'
import { firstMenu } from '@/utils/map-menus'
import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  history: createWebHashHistory(),
  // 映射关系， path =>component
  routes: [
    {
      path: '/',
      redirect: '/home',
    },
    {
      path: '/login',
      component: () => import('../views/login/index.vue'),
    },
    {
      path: '/home',
      name: 'home',
      component: () => import('../views/home/index.vue'),
      children: [],
    },
    {
      path: '/:pathMatch(.*)',
      component: () => import('../views/404/index.vue'),
    },
  ],
})

//路由守卫
router.beforeEach((to, from) => {
  const token = localStorage.getItem(TOKEN)
  if (to.path === '/home' && !token) {
    return '/login'
  }

  if (to.path === '/home') {
    return firstMenu?.url
  }
})

export default router
